package dao

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

type Department struct {
	Uid int `gorm:"column:uid" json:"uid"`
	DpId int `gorm:"column:dp_id" json:"dp_id"`
	Fid int `gorm:"column:f_dpid" json:"f_dpid"`
	Name string `gorm:"column:name" json:"name"`
	Desc string `gorm:"column:desc" json:"desc",`
	BaseModel
}
/**
	添加部门
 */
func (t *Department)Create(d map[string]interface{}) (bool,int) {

	var addDep Department

	if v,ok := d["uid"];ok{
		addDep.Uid = v.(int)
	}
	if v, ok := d["name"];ok{
		addDep.Name = v.(string)
	}
	if v,ok := d["desc"];ok{
		addDep.Desc = v.(string)
	}
	if v,ok := d["f_dpid"];ok{
		fid,_ := strconv.Atoi(v.(string))
		addDep.Fid = fid
	}
	if v,ok := d["uid"];ok{
		addDep.Uid = v.(int)
	}

	addDep.Ctime = XTime{
		time.Now(),
	}
	err := db.Create(&addDep).Error
	b := true
	if err != nil{
		b = false
	}

	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return b,id[0]
}
/**
	软删除
 */
func (t *Department)Delete(dp_id int) bool {

	w := make(map[string]interface{})
	w["dp_id"] = dp_id

	err := db.Model(&t).Where(w).Update("d_time",time.Now()).Error

	b := true
	if err != nil{
		b = false
	}
	return b

}
func (t *Department)Update(w map[string]interface{},d map[string]interface{}) bool {

	if v,ok := d["f_dpid"];ok{
		t.Fid = v.(int)
	}
	if v,ok := d["name"];ok{
		t.Name = v.(string)
	}
	if v,ok := d["desc"];ok{
		t.Desc = v.(string)
	}
	err := db.Model(&t).Where(w).Update(&t).Error
	b := true
	if err != nil {
		b = false
	}
	return b

}
/**
	数据集
 */
func (t *Department)Find(w map[string]interface{},page int,pageSize int)([]*Department,int,error){

	var total int = 0
	var us []*Department
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).
		Where("d_time is NULL").
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("dp_id desc").Find(&us).Error

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}

	// 获取总条数
	db.Model(&t).Where(w).Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return us,total,nil

}
/**
	单条数据
 */
func (t *Department)First(w map[string]interface{}) (bool, *Department) {

	err := db.Where(w).Where("d_time is NULL").First(&t).Error
	if err != nil{
		return false,nil
	}
	fmt.Println(t)
	if t.DpId > 0{
		return true,t
	}
	return false,nil

}

var Dep = &Department{}
